package cn.demo.controller;

import cn.demo.Util.Result;
import cn.demo.service.PasswordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;


/**
 * @Author weizhongli
 * @Date 2020/4/12
 * @Version v1.0
 * @Description 密码修改控制层
 **/
@Controller
public class PasswordController {

    //依赖注入
    @Autowired
    private PasswordService passwordService;
    @Autowired
    private BCryptPasswordEncoder passwordByAuth;

    /*
    * 修改密码
    * */
    @RequestMapping("updatePassword")
    @ResponseBody
    public Result update(String oldPassword, String newPassword, HttpSession session) {
        //获取session中存放的登录用户的userCode
        String userCode = (String) session.getAttribute("userCode");
        String userPassword = passwordService.selectNewPassword(userCode);
        BCryptPasswordEncoder encode = new BCryptPasswordEncoder();
        if (encode.matches(oldPassword,userPassword)) {
            //旧密码与新密码一致
            newPassword  = passwordByAuth.encode(newPassword);
            int i = passwordService.update(newPassword, userCode);
            if (i == 1) {
                session.removeAttribute("userCode");
                return new Result(true, "修改成功", 1);
            } else {
                return new Result(false, "修改失败", 0);
            }
        }
        return new Result(false, "密码不正确", 3);
    }
}
